// 购物车
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');
const { Products } = require('./product');
const session = require('koa-session');


const ShopCar = sequelize.define('shopCar', {
    id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
    },
    number: {
        type: DataTypes.BIGINT,
        allowNull: false,
    },
    productId: {
        type: DataTypes.BIGINT,
        allowNull: false,
    },
    userId: {
        type: DataTypes.UUID,
        allowNull: false,
    }
}, {

});


ShopCar.sync();


const shopCarModel = {
    async getShopCar(ctx) {
        const params = ctx.query;
        // const count = await ShopCar.count();
        const {offset = 0, limit = 10} = params;
        
        const { count, rows } = await ShopCar.findAndCountAll(
            {
                limit: parseInt(limit),
                offset: parseInt(offset),
                raw: true,
                where: {
                    userId: ctx.session.sessionData.id,
                }
            }
        );
        console.log(rows);
        const productIds = rows.map(row => {
            return row.productId;
        });

        if (0 !== count) {
            const productInfo = await Products.findAll({
                where: {
                    id: {[Op.in]: productIds},
                },
                raw: true,
            });
            productInfo.forEach(product => {
                rows.forEach(car => {
                    if (car.productId === product.id) {
                        product.id = car.id;
                        product.productId = car.productId;
                        product.number = car.number;
                        product.userId = car.userId;
                    }
                });
            });

            ctx.pageRes({
                limit,
                offset,
                list: productInfo,
                total: count,
            });
        } else {
            ctx.pageRes({
                limit,
                offset,
                list: rows,
                total: count,
            });
        }
    },

    async addShopCar(ctx) {
        const params = ctx.request.body;

        const validFlag = this.validProduct(ctx, params);
        if (validFlag) {
            // 验证产品是否是存在
            const product = await Products.findOne({
                where: {id: params.productId},
                raw: true,
            });
            if (product) {
                // 验证购物车中是否存在相同的产品
                const shopCarProduct = await ShopCar.findOne({
                    where: {productId: params.productId},
                    raw: true,
                });
                // 如果购物车存在相同的商品，则增加数量
                console.log(shopCarProduct);
                if (!!shopCarProduct) {
                    await ShopCar.update({
                        number: params.number + shopCarProduct.number,
                    }, {
                        where: {
                            productId: params.productId,
                        },
                    });
                } else {
                    poducts = await ShopCar.create({
                        ...params,
                        userId: ctx.session.sessionData.id
                    });
                }

                ctx.success('增加成功！');
            } else {
                ctx.errorParams('未查找到商品！');
            }
        }
    },
    validProduct(ctx, params) {
        if (!params.productId) {
            ctx.errorParams('商品id不存在！');
            return false;
        } else if (!params.number) {
            ctx.errorParams('商品数量不存在！');
            return false;
        } else {
            return true;
        }
    },
    validCar(ctx, params) {
        if (!params.id) {
            ctx.errorParams('id不存在！');
            return false;
        } else if (!params.number) {
            ctx.errorParams('商品数量不存在！');
            return false;
        } else {
            return true;
        }
    },
    async deleteShopCar(ctx)  {
        const deleteId = ctx.request.body.id;
        if (!deleteId) {
            ctx.errorParams('id不存在！');
        } else {
            await ShopCar.destroy({
                where: {
                    id: deleteId,
                }
            });

            ctx.success('删除成功！', {
                id: deleteId,
            })
        }
        
    },
    async editShopCar(ctx)  {
        const params = ctx.request.body;
        const editId = params.id;
        const validFlag = this.validCar(ctx, params);
        if (validFlag) {
            await ShopCar.update({
                number: params.number,
            }, {
                where: {
                    id: editId
                },
            });
            
            ctx.success('修改成功', {
                id: editId,
            });
        }
        
    }
    
};


module.exports = {
    shopCarModel,
    ShopCar
};